package com.tca.common.learning.webflux.springboot.reactor.handler;


import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author zhoua
 */
@Component
public class ReactorHandler {

    /**
     * 获取时间
     * @param request
     * @return
     */
    public Mono<ServerResponse> getTime(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(LocalDateTime.now().format(DateTimeFormatter.ISO_TIME)), String.class);
    }

    /**
     * 获取日期
     * @param request
     * @return
     */
    public Mono<ServerResponse> getDate(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE)), String.class);
    }

    /**
     * 每隔1s推送
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> sendTimePerSec(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(
                Flux.interval(Duration.ofSeconds(1)).
                        map(l -> LocalDateTime.now().format(DateTimeFormatter.ISO_TIME)),
                String.class);
    }


}
